package com.rd.server.modules.wechat.controller;

import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.dev33.satoken.secure.SaBase64Util;
import com.rd.common.model.Result;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * 微信模块
 * @ClassName WechatController
 * @Description TODO
 * @Author zyy
 * @Date 2025/6/14 22:36
 * @Version 1.0
 **/
@RestController
@RequestMapping("/wechat")
@RequiredArgsConstructor
public class WechatController {

    private final WxMaService wxMaService;

    public static final String ROOM_PATH = "/pages/room/index?roomId=";

    /**
     * 获取小程序码
     *
     * @param roomId 房间ID
     * @return
     */
    @GetMapping("getwxacode/{roomId}")
    public Result<String> getwxacode(@PathVariable("roomId") String roomId
            , @RequestParam(value = "version", required = false) String version) throws WxErrorException {
        version = StringUtils.isNoneBlank(version) ? version : "trial";
        String path = ROOM_PATH + roomId;
        WxMaQrcodeService qrcodeService = wxMaService.getQrcodeService();
        byte[] wxaCodeBytes = qrcodeService.createWxaCodeBytes(path, version, 430, true, null, true);
        // 转base64
        String base64Image = SaBase64Util.encodeBytesToString(wxaCodeBytes);
        // 添加 base64 图片前缀
        String base64ImageWithPrefix = "data:image/png;base64," + base64Image;
        return Result.success(base64ImageWithPrefix);
    }

}
